package com.xuecheng.ucenter.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.ucenter.mapper.XcMenuMapper;
import com.xuecheng.ucenter.mapper.XcUserMapper;
import com.xuecheng.ucenter.model.dto.AuthParamsDto;
import com.xuecheng.ucenter.model.dto.XcUserExt;
import com.xuecheng.ucenter.model.po.XcMenu;
import com.xuecheng.ucenter.model.po.XcUser;
import com.xuecheng.ucenter.service.AuthService;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 自定义UserDetailsService，进行用户登录认证
 */
@Service
public class UserServiceImpl implements UserDetailsService {

    @Autowired
    XcUserMapper xcUserMapper;

    @Autowired
    ApplicationContext applicationContext;

    @Autowired
    XcMenuMapper xcMenuMapper;

    /**
     * 根据账号查询用户信息
     *
     * @param s 账号
     */
    // 传入请求的参数就是AuthParamsDto
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        // 将传入的json转成AuthParamsDto对象
        AuthParamsDto authParamsDto = null;
        try {
            authParamsDto = JSON.parseObject(s, AuthParamsDto.class);
        } catch (Exception e) {
            throw new RuntimeException("请求认证参数不符合要求！！！");
        }
        // 认证类型
        String authType = authParamsDto.getAuthType();
        // 根据认证类型从spring容器取出指定的bean
        String beanName = authType + "_authservice";
        AuthService authService = applicationContext.getBean(beanName, AuthService.class);
        // 开始认证
        XcUserExt user = authService.execute(authParamsDto);

        return getUserPrincipal(user);
    }

    @Nullable
    private UserDetails getUserPrincipal(XcUserExt  user) {

        //取出数据库存储的正确密码
        String password = user.getPassword();
        //用户权限，如果不加报错：Cannot pass a null GrantedAuthority collection
        String[] authorities = {"test"};
        List<XcMenu> xcMenus = xcMenuMapper.selectPermissionByUserId(user.getId());
        if (xcMenus.size() > 0) {
            List<String> permissions = new ArrayList<>();
            xcMenus.forEach(m -> {
                // 拿到了用户的权限标识符集合
                permissions.add(m.getCode());
            });
            // 转成数组，封装到token中
            authorities = permissions.toArray(new String[0]);
        }
        //扩展用户信息，将user对象转成json串
        user.setPassword(null);
        String XCUser = JSON.toJSONString(user);
        //创建UserDetails对象，权限信息待实现授权功能时再向UserDetail中加入
        //封装得到的UserDetails对象，根据这个对象生成令牌，交给SpringSecurity框架去进行校验
        UserDetails userDetails
                = User
                .withUsername(XCUser)
                .password(password)
                .authorities(authorities)
                .build();

        return userDetails;
    }


}